#!/usr/bin/perl

require LWP::UserAgent;
use HTTP::Request::Common;
use Archive::Zip qw (:ERROR_CODES :CONSTANTS );
use Digest::MD5 qw(md5 md5_hex md5_base64);
use File::stat;

# Change : Modify the file name to compress the _'s down to 1.
# Change : Detect the cover image (SKU.gif?, change to book_title.gif, or something
# Change : Make this all happen on the target system?  copy_file/mv SKU_______/mv SKU____/...

%::http_passwords = ();
my $current_realm;

{
    package RequestAgent;
    @ISA = qw(LWP::UserAgent);

    sub new
    { 
	my $self = LWP::UserAgent::new(@_);
	$self->agent("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12");
	$self->timeout(30);
	$self->env_proxy;
	$self->cookie_jar({ file =>"$ENV{HOME}/.cookies.txt", autosave => 1 });
	
	$self;
    }
}

# Fill in the tags of form VALUE_TAG with the specified values.
# template - the source file (needing changing)
# outfile - the destination file
# filler - has of the format "tag" => "value".
sub populateTemplate {
    my ($template, $outfile, %filler) = @_;
    print "populateTemplate - Template:$template, Outfile:$outfile\n" if ($template_debug != 0);

    open TEMPLATE, "<$template" or die "Unable to open $template for reading $!";
    open OUT_FILE, ">$outfile" or die "Unable to open $outfile for writing $!";

    while (<TEMPLATE>) {
	my $line = $_;
	foreach my $regex (keys %filler) {
	    print "$regex ==> ", $filler{$regex},"\n" if ($regex_debug != 0);
	    $line =~ s/VALUE_$regex/$filler{$regex}/g;
	}
	print "Replaced line $line\n" if ($regex_debug != 0);
	print OUT_FILE $line;
    }
    close TEMPLATE;
    close OUT_FILE;
}

my $book_url = @ARGV[0];
my $author;
my $title;
my $zip_url;
my $zip_url_plist;
my $SKU;
my $productID = "";
my $md5;
my $size;
my $description;
my $date = time();
my $copy_files;
my $remove_files;
my $debug = 1;
my $debug_content = 0;
my $debug_copy = 0;

# Get the containing web page.

my $ua = RequestAgent->new;

if (scalar @ARGV != 1) {
    die "You forgot the URL, idiot!\n";
}
print "Retrieving book details\n" unless $debug == 0;

if ( -f "baen_books/odd_books/$book_url") {
    # read the details from the file.
    open DETAILS, "<baen_books/odd_books/$book_url" or die "Unable to open $book_url for reading $!";
    ($title, $author, $SKU, $zip_url, $description) = <DETAILS>;
    chomp($title, $author, $SKU, $zip_url, $description);
    $zip_url_plist = $zip_url;
    close DETAILS
} else {
    my $response = $ua->get($book_url);
    print "Parsing response...\n" unless $debug == 0;

    if (!$response->is_success) {
	die "$book_url" . $response->status_line;
    } 
    
    # Look for 
    # Meta description is the book title
    # Author is in Keywords, between the second to last and the last ","?
    
    if ($response->content =~ /meta NAME=\"description\" CONTENT=\"(.*?)\"/m ) {
	$title = $1;
    } else {
	print $response->content unless $debug_content == 0;
	die $book_url . " OMG we didn't find the title!";
    }
    
    $title =~ s/ by .*? - WebScription.*$//g;
    
    if ($response->content =~ /ProductID=(.*?)&/m ) {
	$productID = $1;
    } else {
	print $response->content unless $debug_content == 0;
	die $book_url . " OMG we didn't find the productID!";
    }
    
    if ($response->content =~ /meta NAME=\"keywords\" CONTENT=\"$title,([^,]+),/) {
	$author = $1;
    } else {
	print $response->content unless $debug_content == 0;
	die $book_url . " OMG we didn't find the Author!";
    }
    
    if ($response->content =~ /SKU=([[:alnum:]]+)&/) {
	$SKU = $1;
    } else {
	print $response->content unless $debug_content == 0;
	die $book_url . " OMG we didn't find the SKU!";
    }
    
    $zip_url = "http://www.webscription.net/SendZip.aspx?SKU=$SKU&ProductID=$productID&format=H";
    $zip_url_plist = "http://www.webscription.net/SendZip.aspx?SKU=$SKU&amp;ProductID=$productID&amp;format=H";
    
    if ($response->content =~ /<div><br \/>(.*?)<\/div>/s ) {
	$description = $1;
    } elsif ($response->content =~ /<h3 align="center">(.*?)<\/h3>/s ) {
	$description = $1;
    } elsif ($response->content =~ /<h3>(.*?)<\/h3>/s ) {
	$description = $1;
    } elsif ($response->content =~ /<font SIZE="3">(.*?)<\/font>/s ) {
	$description = $1;
    } else {
	$description = "none found";
    }
    
    $description =~ s/<.*?>//g;
    $description =~ s/&nbsp;/ /g;
    $description =~ s/&mdash;/-/g;
    $description =~ s/[^[:ascii:]]//g;
    

}

print "\tTitle\t$title\n" unless $debug == 0;
print "\tPID\t$productID\n" unless $debug == 0;
print "\tAuthor\t$author\n" unless $debug == 0;
print "\tSKU\t$SKU\n" unless $debug == 0;
print "\tdesc\t$description\n" unless $debug == 0;

# Get the html .zip file
my $book_zip = "baen_books/zips/${SKU}_${productID}.zip";
if ( ! -f $book_zip ) {
    print "Retrieving book zip file: $zip_url -> $book_zip\n" unless $debug == 0;
    my $mirror_result = $ua->mirror($zip_url, $book_zip);
    #system("wget -O $book_zip -o wget.log '$zip_url'");
}


print "Got the zip! $book_zip\n" unless $debug == 0;

# We've got a zip file.

# Size and md5
open(FILE, $book_zip) or die $book_url . "Can't open '$file' for hash: $!";
binmode(FILE);
$md5 = Digest::MD5->new->addfile(*FILE)->hexdigest;
close(FILE);
print "\thash\t$md5\n" unless $debug == 0;
$sb = stat($book_zip);
$size = $sb->size;
print "\tsize\t$size\n" unless $debug == 0;

my $zipFile = Archive::Zip->new();
die $book_url . "read error" unless ($zipFile->read($book_zip) == AZ_OK);

# Get the file list from the .zip file.
my @files = $zipFile->memberNames();
print "\tfileCount\t".scalar(@files)."\n" unless $debug == 0;

# Now write out the installer.

$remove_files = "           <array>
             <string>RemovePath</string>
             <string>~/Media/EBooks/$title</string>
           </array>";
$remove_old_files = "           <array>
             <string>RemovePath</string>
             <string>/var/root/Media/EBooks/$title</string>
           </array>";


$copy_files = "";
# First we take an extra copy of the cover image.
$copy_files .="           <array>
             <string>CopyPath</string>
             <string>$SKU.jpg</string>
             <string>~/Media/EBooks/$title/cover.jpg</string>
           </array>\n";

foreach my $file (@files) {
    my $destfile = $file;
    if ( $destfile =~ /\.htm$/ ) {
	$destfile =~ s/$SKU/Chapter/g;
	$destfile =~ s/(_)+/_/g;
    }
    print "$file => $destfile\n" unless $debug_copy == 0;
    $copy_files .="           <array>
             <string>CopyPath</string>
             <string>$file</string>
             <string>~/Media/EBooks/$title/$destfile</string>
           </array>\n";
}

# Create the xml document.

my %keysHash = 
    ( "TITLE"  => $title,
      "AUTHOR" => $author,
      "URL" => $zip_url_plist,
      "SIZE" => $size,
      "HASH" => $md5,
      "HOME" => $book_url,
      "DESCRIPTION" => $description,
      "DATE" => $date,
      "COPY_FILES"=> $copy_files,
      "REMOVE_FILES"=> $remove_files,
      "REMOVE_OLD_FILES"=> $remove_old_files
      );

populateTemplate("templates/baen_books.xml", "baen_books/plists/${title}.plist", %keysHash);

print "done!\n";
